package pri.service.product;

import cn.hutool.core.util.NumberUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;
import pri.common.Common;
import pri.dao.*;
import pri.pojo.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baima46
 * @since 2019-07-07
 */
@Service
@Transactional
public class ProductServiceImpl implements ProductService {
    @Autowired
    ProductMapper productMapper;
    @Autowired
    ProductImageMapper productImageMapper;
    @Autowired
    CollectionProductMapper collectionProductMapper;
    @Autowired
    CategoryMapper categoryMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    ProductCommentMapper productCommentMapper;
    @Autowired
    UserMapper userMapper;



    @Override
    public Integer add(ProductInfo productInfo) {
        Integer id = Integer.parseInt(Common.getUUID(8));

        if(!check(productInfo)){
            return 0;
        }
        Product product = infoToProduct(productInfo);
        product.setProductId(id);
        product.setType(id);
        addImg(productInfo.getImgs(),id);

        return productMapper.insertSelective(product);
    }

    private void addImg(List<String> imgs, Integer productId) {
        if(imgs == null || productId == null) return;

        ProductImage productImage = new ProductImage();
        productImage.setProductId(productId);

        int i = 1;
        for (String img : imgs) {
            productImage.setUrl(img);
            productImage.setType(i++);
            productImage.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));

            productImageMapper.insertSelective(productImage);
        }

    }

    private Product infoToProduct(ProductInfo productInfo) {
        Product product = new Product();
        product.setName(productInfo.getName());
        product.setPrice(productInfo.getPrice());
        product.setConcessionalPrice(productInfo.getConcessionalPrice());
        product.setStock(productInfo.getStock());
        product.setCategoryId(productInfo.getCategoryId());
        product.setColor(productInfo.getColor());
        product.setStateId(productInfo.getStateName()==null?1000:100);
        product.setDetail(productInfo.getDetail());

        product.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));

        return product;
    }

    private boolean check(ProductInfo productInfo) {
        if(productInfo==null){
            return false;
        }

        Map<String,String> errors = new HashMap<>();
        if(productInfo.getName()==null || "".equals(productInfo.getName())){
            errors.put("name","商品名不能为空！");
        }else if(productInfo.getName().length()>100){
            errors.put("name","商品名太长了，请不要超过100个字符！");
        }

        if(productInfo.getPrice()==null){
            errors.put("price","价格不能为空！");
        }else if(productInfo.getPrice()<0){
            errors.put("price","请输入合法的价格！");
        }

        if(productInfo.getStock()==null){
            errors.put("stock","库存不能为空！");
        }else if(productInfo.getStock()<0){
            errors.put("stock","请输入合法的库存！");
        }

        if(productInfo.getCategoryId()==null){
            errors.put("categoryId","类型不能为空！");
        }else if(productInfo.getPrice()<0){
            errors.put("categoryId","请输入合法的类型！");
        }

        if(productInfo.getColor()==null || "".equals(productInfo.getColor())){
            errors.put("categoryId","颜色不能为空！");
        }

        if(productInfo.getDetail()==null || "".equals(productInfo.getDetail())){
            errors.put("categoryId","商品详情不能为空！");
        }


        if(errors.size()>0){
            return false;
        }

        return true;
    }

    @Override
    public boolean delete(Integer id) {

        return productMapper.deleteByPrimaryKey(id)>0;
    }

    @Override
    public boolean update(Product product) {
        Product product1 = productMapper.selectByPrimaryKey(product.getProductId());
        if(product1.getStateId()==product.getStateId()){
            return false;
        }

        product.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));

        return productMapper.updateByPrimaryKeySelective(product)>0;

    }

    @Override
    public int allBrow() {
        ProductExample example = new ProductExample();
        List<Product> products = productMapper.selectByExample(example);

        int number = 0;

        for (Product product : products) {
            number += product.getLookNum();
        }

        return number;
    }

    @Override
    public int countByExample(ProductInfo product) {
        ProductExample example = new ProductExample();

        return (int)productMapper.countByExample(example);
    }

    @Override
    public ProductInfo findById(Integer id,String userId) {
        Product product = productMapper.selectByPrimaryKey(id);
        // 状态码大于200 普通用户不可见
        if(product.getStateId()>200){
            return null;
        }

        Product product1 = new Product();
        product1.setProductId(id);
        product1.setLookNum(product.getLookNum()+1);
        product1.setHeat(product.getHeat()+2);

        productMapper.updateByPrimaryKeySelective(product1);

        ProductInfo productInfo = productToInfo(product);

        // 获取同类其他颜色商品
        productInfo.setOtherColorProducts(getOtherColorProducts(product.getProductId(),product.getType()));
        // 判断用户是否收藏过该商品
        productInfo.setIsCollection(isCollection(id,userId));

        // 判断用户是否可以评论
//        productInfo.setCanComent(canComment(id,userId));

        return productInfo;
    }

    private Integer canComment(Integer productId, String userId) {


        return 0;
    }

    private List<ProductComment> selectProductComments(Integer id) {
        ProductCommentExample example = new ProductCommentExample();
        example.setOrderByClause("create_time desc");
        example.createCriteria().andProductIdEqualTo(id);

        List<ProductComment> comments = productCommentMapper.selectByExample(example);
        for (ProductComment comment : comments) {
            User user = userMapper.selectByPrimaryKey(comment.getUserId());
            if(user!=null && user.getNickName()!=null){
                comment.setUserId(user.getNickName());
            }else{
                comment.setUserId("用户"+comment.getUserId());
            }
        }

        return comments;
    }

    private Map<String,Integer> selectProductCommentsByscore(Integer id) {
        Map<String,Integer> map = new HashMap<>();

        ProductCommentExample example = new ProductCommentExample();
        // 1星评论
        example.createCriteria().andProductIdEqualTo(id).andScoreEqualTo(2);
        map.put("1", (int) productCommentMapper.countByExample(example));
        // 2星评论
        example.clear();
        example.createCriteria().andProductIdEqualTo(id).andScoreEqualTo(4);
        map.put("2", (int) productCommentMapper.countByExample(example));
        // 3星评论
        example.clear();
        example.createCriteria().andProductIdEqualTo(id).andScoreEqualTo(6);
        map.put("3", (int) productCommentMapper.countByExample(example));
        // 4星评论
        example.clear();
        example.createCriteria().andProductIdEqualTo(id).andScoreEqualTo(8);
        map.put("4", (int) productCommentMapper.countByExample(example));
        // 5星评论
        example.clear();
        example.createCriteria().andProductIdEqualTo(id).andScoreEqualTo(10);
        map.put("5", (int) productCommentMapper.countByExample(example));

        return map;
    }

    private List<ProductInfo> getOtherColorProducts(Integer productId,Integer type) {
        ProductExample example = new ProductExample();
        example.createCriteria().andProductIdNotEqualTo(productId).andTypeEqualTo(type);

        return productToInfo(productMapper.selectByExample(example));
    }

    @Override
    public List<ProductInfo> findByExample(ProductInfo productInfo, Page page) {
        ProductExample example = new ProductExample();
        example.setOrderByClause("create_time desc");
        ProductExample.Criteria criteria = example.createCriteria();

        if(productInfo != null){
            // 排序
            if(productInfo.getOrderBy()==null){
                example.setOrderByClause("heat desc");
            }else{
                switch (productInfo.getOrderBy()){
                    case 0: example.setOrderByClause("heat desc");break;
                    case 1: example.setOrderByClause("name");break;
                    case 2: example.setOrderByClause("name desc");break;
                    case 3: example.setOrderByClause("price");break;
                    case 4: example.setOrderByClause("price desc");break;
                }
            }

            // 根据分类查询
            if(productInfo.getCategoryId()!=null && productInfo.getCategoryId()!=100){
                criteria.andCategoryIdEqualTo(productInfo.getCategoryId());
            }
            // 根据商品名查询
            if(productInfo.getName()!=null && !"".equals(productInfo.getName())){
                criteria.andNameLike("%%"+productInfo.getName()+"%%");
            }
            // 根据颜色查询
            if(productInfo.getColor()!=null && !"".equals(productInfo.getColor())){
                criteria.andColorEqualTo(productInfo.getColor());
            }
            // 根据价格查询
            if(productInfo.getLowPrice()!=null){
                if(productInfo.getHighPrice()!=null && productInfo.getHighPrice()>productInfo.getLowPrice()){
                    criteria.andPriceBetween(productInfo.getLowPrice(),productInfo.getHighPrice());
                }else{
                    criteria.andPriceGreaterThanOrEqualTo(productInfo.getLowPrice());
                }
            }else if(productInfo.getHighPrice()!=null){
                criteria.andPriceLessThanOrEqualTo(productInfo.getHighPrice());
            }
        }

        // 如果选择了分页
        if(page != null){
            page.setTotalRows((int)productMapper.countByExample(example));
            example.setStartRow(page.getStartRow());
            example.setPageRows(page.getPageRows()<1?10:page.getPageRows());
        }

        // 获取所有满足条件的商品主信息
        List<Product> products = productMapper.selectByExample(example);

        // 将所有的Product封装为ProductInfo
        List<ProductInfo> productInfos = productToSimpleInfo(products);

        return productInfos;
    }

    @Override
    public Integer collection(Integer productId, String userId) {
        Product product = productMapper.selectByPrimaryKey(productId);
        if(product.getStateId()>200){
            return 0;
        }
        CollectionProductExample example = new CollectionProductExample();
        example.createCriteria().andProductIdEqualTo(productId).andUserIdEqualTo(userId);
        if(collectionProductMapper.countByExample(example)>0){
            return 0;
        }

        CollectionProduct collectionProduct = new CollectionProduct();
        collectionProduct.setProductId(productId);
        collectionProduct.setUserId(userId);
        collectionProduct.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));

        addHeat(product,5);

        return collectionProductMapper.insertSelective(collectionProduct)>0?1:0;
    }

    @Override
    public Integer cancelCollection(Integer productId, String userId) {
        CollectionProductExample example = new CollectionProductExample();
        example.createCriteria().andProductIdEqualTo(productId).andUserIdEqualTo(userId);

        return collectionProductMapper.deleteByExample(example)>0?1:0;
    }


    @Override
    public List<ProductInfo> getCollections(String userId,int number) {
        CollectionProductExample example = new CollectionProductExample();
        example.setOrderByClause("create_time desc");
        example.createCriteria().andUserIdEqualTo(userId);

        List<CollectionProduct> collectionProducts = collectionProductMapper.selectByExample(example);
        if(collectionProducts.size()>number){
            collectionProducts = collectionProducts.subList(0,number);
        }

        List<ProductInfo> productInfolist = new ArrayList<>();
        ProductInfo productInfo;
        for (CollectionProduct collectionProduct : collectionProducts) {
            productInfo = productToInfo(productMapper.selectByPrimaryKey(collectionProduct.getProductId()));
            productInfo.setIsCollection(1);
            productInfolist.add(productInfo);
        }

        return productInfolist;
    }


    @Override
    public List<Category> hotCategory() {
        CategoryExample example = new CategoryExample();
        // 查询手机下的全部分类
        example.createCriteria().andParentIdEqualTo(501000);

        List<Category> categories = categoryMapper.selectByExample(example);

        for (Category category : categories) {
            ProductExample productExample = new ProductExample();
            productExample.createCriteria().andCategoryIdEqualTo(category.getId());
            category.setNumber((int) productMapper.countByExample(productExample));
        }

        // 按分类中手机数量降序排序
        Collections.sort(categories, (o1, o2) -> o2.getNumber()-o1.getNumber());

        if(categories.size()>6){
            categories = categories.subList(0, 6);
        }

        return categories;
    }

    @Override
    public ProductInfo transQuery(ProductInfo old, ProductInfo newo) {

        if(newo.getName()!=null){
            old.setName(newo.getName());
        }
        if(newo.getCategoryId()!=null){
            if(newo.getCategoryId()==100){
                old.setCategoryId(null);
            }else{
                old.setCategoryId(newo.getCategoryId());
            }
        }
        if(newo.getLowPrice()!=null){
            old.setLowPrice(newo.getLowPrice());
        }
        if(newo.getHighPrice()!=null){
            old.setHighPrice(newo.getHighPrice());
        }
        if(newo.getOrderBy()!=null){
            old.setOrderBy(newo.getOrderBy());
        }

        return old;
    }

    @Override
    public List<ProductInfo> mastLook() {
        ProductExample example = new ProductExample();
        example.setOrderByClause("look_num desc");

        List<Product> products = productMapper.selectByExample(example);
        products = products.subList(0,5);


        return productToInfo(products);
    }

    @Override
    public void addHeat(Integer productId, int number) {
        Product product = productMapper.selectByPrimaryKey(productId);

        Product product1 = new Product();
        product1.setProductId(productId);
        product1.setHeat(product.getHeat()+number);

        productMapper.updateByPrimaryKeySelective(product1);
    }

    @Override
    public Integer addComment(ProductComment productComment, String userId) {
        productComment.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));

        addHeat(productComment.getProductId(),7);

        return productCommentMapper.insertSelective(productComment);
    }










    public void addHeat(Product product,int number){
        Product product1 = new Product();
        product1.setProductId(product.getProductId());
        product1.setHeat(product.getHeat()+number);

        productMapper.updateByPrimaryKeySelective(product1);
    }


    public List<ProductImage> selectProductImages(Integer productId){
        ProductImageExample imageExample = new ProductImageExample();
        imageExample.createCriteria().andProductIdEqualTo(productId);

        return productImageMapper.selectByExample(imageExample);
    }

    public List<ProductInfo> productToInfo(List<Product> products){

        return productToInfo(products,null);
    }

    public List<ProductInfo> productToInfo(List<Product> products,String userId){
        List<ProductInfo> productInfos = new ArrayList<>();

        for (Product product : products) {
            ProductInfo productInfo = productToInfo(product);
            // 取每个商品的图片
            productInfo.setImages( selectProductImages(product.getProductId()) );
            // 判断用户是否收藏过该商品
            productInfo.setIsCollection(isCollection(product.getProductId(),userId));
            // 获取星星
            productInfo.setXing(getXing(product.getProductId()));

            productInfos.add(productInfo);

        }

        return productInfos;
    }

    public List<ProductInfo> productToSimpleInfo(List<Product> products){
        List<ProductInfo> productInfos = new ArrayList<>();
        ProductInfo productInfo;
        for (Product product : products) {
            productInfo = productToSimpleInfo(product);

            // 取每个商品的分类
            productInfo.setCategoryName(selectCategoryName(product.getCategoryId()));
            // 设置每个商品的状态
            productInfo.setStateName(setStateName(product.getStateId()));

            productInfos.add(productInfo);
        }

        return productInfos;
    }

    public ProductInfo productToSimpleInfo(Product product){
        ProductInfo productInfo = new ProductInfo();
        if(product==null){
            return productInfo;
        }

        productInfo.setProductId(product.getProductId());
        productInfo.setName(product.getName());
        productInfo.setPrice(product.getPrice());
        productInfo.setConcessionalPrice(product.getConcessionalPrice());
        productInfo.setStock(product.getStock());
        productInfo.setDepict(product.getDepict());
        productInfo.setCategoryId(product.getCategoryId());
        productInfo.setCreateTime(product.getCreateTime());
        productInfo.setUpdateTime(product.getUpdateTime());
        productInfo.setStateId(product.getStateId());
        productInfo.setMsg(product.getMsg());
        productInfo.setColor(product.getColor());
        productInfo.setType(product.getType());
        productInfo.setDetail(product.getDetail());

        // 获取商品图片
        productInfo.setImages(selectProductImages(product.getProductId()));


        return productInfo;
    }

    private String setStateName(Integer stateId) {
        if(stateId==null) return null;
        if(stateId<200){
            return "在售";
        }
        if(stateId<300){
            return "暂停销售";
        }
        if(stateId<400){
            return "售罄";
        }
        if(stateId<500){
            return "禁售";
        }

        return "未上架";
    }

    private String selectCategoryName(Integer categoryId) {
        Category category = categoryMapper.selectByPrimaryKey(categoryId);

        if(category!=null){
            return category.getName();
        }

        return null;
    }

    private Integer getXing(Integer id) {
        ProductCommentExample example = new ProductCommentExample();
        example.createCriteria().andProductIdEqualTo(id);
        List<ProductComment> comments = productCommentMapper.selectByExample(example);

        Integer score = 10;
        for (ProductComment comment : comments) {
            score += comment.getScore();
        }

        return score/(1+comments.size());
    }

    private Integer isCart(Integer productId,String userId) {
        if(userId==null || productId==null){
            return null;
        }
        CartExample example = new CartExample();
        example.createCriteria().andProductIdEqualTo(productId.toString()).andUserIdEqualTo(userId);

        return cartMapper.countByExample(example)>0?1:0;
    }

    public Integer isCollection(Integer productId,String userId){
        if(userId==null || productId==null){
            return null;
        }
        CollectionProductExample example = new CollectionProductExample();
        example.createCriteria().andProductIdEqualTo(productId).andUserIdEqualTo(userId);

        return collectionProductMapper.countByExample(example)>0?1:0;
    }

    public ProductInfo productToInfo(Product product){
        ProductInfo productInfo = productToSimpleInfo(product);

        // 获取商品的评论
        List<ProductComment> comments = selectProductComments(product.getProductId());
        productInfo.setProductComments(comments);

        // 获取各评分的评论数量
        productInfo.setProductCommentsByScore(selectProductCommentsByscore(product.getProductId()));

        // 总分数
        Integer allScore = 10;
        for (ProductComment productComment : comments) {
            allScore += productComment.getScore();
        }

        // 平均分数
        double v = allScore * 0.5 / (1 + comments.size());
        productInfo.setAvgScore(NumberUtil.round(v>5.0?5.0:v,1));

        // 星数
        int x = allScore / (1 + comments.size());
        productInfo.setXing(x>10?10:x);

        return productInfo;
    }

}
